<?php
class LZ_Photo_Album
{
	var $table = 'album';
	var $id = 'album_id';

	function LZ_Photo_Album()
	{
		$this->table = LZ_MYSQL_PREFIX.$this->table;
	}

	function add( $data )
	{
		global $db;
		$data['create_time'] = time();
		if (!$data['status']) $data['status'] = 'public';
		$sql = make_insert_sql($this->table, $data);
		if ($db->query($sql))
		{
			$_id = $db->insert_id();
			include_once(LZ_BASEPATH.'model/search.php');
			$search = new LZ_Search;
			$s = $data['tag'].' '.$data['name'];
			if ($s) $search->add('album',$id,$s);
			return $_id;
		}
	}

	function exists($name)
	{
		global $db;
		$r = $db->query("SELECT * FROM $this->table WHERE `name`='$name' LIMIT 1");
		if($db->num_rows($r)>0)
		{
			$arr = $db->fetch_array($r);
			return $arr[$this->id];
		}
		else return false;
	}

	function get_list($data=array())
	{
		global $db;
		$_s = $data['select']?$data['select']:'*';
		$sql = "SELECT $_s FROM `{$this->table}` WHERE 1=1 ";
		if (isset($data['status']))
			$sql.=" AND `status`='".$data['status']."' ";
		if (isset($data['album_id']))
			$sql.=" AND $this->album_id='".$data['album_id']."' ";
		if (isset($data['photo_id']))
			$sql.=" AND $this->id='".$data['photo_id']."' ";
		$sql.= " ORDER BY order_id DESC, ";
		$sql.= ($data['order'])?$data['order']:' update_time ';
		$sql.= ($data['asc'])?' ASC':' DESC';
		
		if ($data['from'] && $data['total'])
		{
			$sql.=" LIMIT ".$data['from'].",".$data['total'];
		}
		else if ($data['total'])
		{
			$sql.=" LIMIT ".$data['total'];
		}
		$sql.= ';';
		return $db->get_all($sql);
	}

	function get_one($id)
	{
		global $db;
		$sql = "SELECT * FROM $this->table WHERE $this->id = '$id' LIMIT 1";
		return $db->get_one($sql);
	}

	function get_one_by_name($name)
	{
		global $db;
		$sql = "SELECT * FROM $this->table WHERE `name` = '$name' LIMIT 1";
		return $db->get_one($sql);
	}
	
	function delete($data = array())
	{
		global $db;
		if(!is_array($data))
			$data = array($data);
		$ids = '';
		foreach($data as $id)
			$ids .= $id.',';
		$ids = substr($ids, 0, -1);
		$sql = "DELETE FROM $this->table WHERE $this->id IN ($ids)";
		if ( $db->query($sql))
		{
			include_once(LZ_BASEPATH.'model/search.php');
			$search = new LZ_Search;
			foreach($data as $id)
			{
				$search->delete('album',$id);
			}
			return true;
		}
	}
	
	function add_viewed($id)
	{
		global $db;
		$sql = "UPDATE $this->table SET viewed = viewed+1 WHERE $this->id='$id'";
		return $db->query($sql);
	}
	
	function update($id, $data = array())
	{
		global $db;
		if (!$id) return;
		$data['update_time'] = time();
		$sql = make_update_sql($this->table, $data, array($this->id => $id));
		if ($db->query($sql))
		{
			include_once(LZ_BASEPATH.'model/search.php');
			$search = new LZ_Search;
			$s = $data['tag'].' '.$data['title'];
			if ($s) $search->add('album',$id,$s);
			return true;
		}
	}
}
?>
